import { useCallback, useMemo, useState } from 'react'
import { Button, Pagination, Typography } from 'antd'
import { favorFilterList } from '@/api/favor.ts'
import { initPageType, message, usePageChange } from '@hs-admin/utils'
import { importFilterData } from '@/api/batchQuery.ts'

const initPage: initPageType = {
  current: 1,
  total: 0,
  pageSize: 10
}

const { Text } = Typography
export const useAddByQuery = (theId: string, tableId: string, resetCall: () => void) => {
  const [data, setData] = useState([])

  const request = useCallback(
    async (page: number, pageSie: number) => {
      const res = await favorFilterList({
        page,
        page_size: pageSie,
        release_item_id: tableId
      })
      setData(res.items)
      return res.total
    },
    [tableId]
  )

  const { pagination, resetPageAndTriggerRequest } = usePageChange(initPage, request)

  const getQuery = (row: any) => {
    const arr: Array<{
      name: string
      config: {
        values?: Array<{
          show: string
        }>
        start?: {
          show: string
        }
        end?: {
          show: string
        }
      }
    }> = row.filters?.items ?? []
    let str = row.filters?.keywords ? `搜索(${row.filters?.keywords})` : ''
    arr.forEach((item) => {
      let values = ''
      if (item.config.values) {
        values = item.config.values.map((it) => it.show).join('，')
      } else {
        values = `${item.config.start?.show ?? '不限'} 到 ${item.config.end?.show ?? '不限'}`
      }
      str += `${item.name}(${values})`
    })
    return str
  }

  return useMemo(
    () => ({
      children: (
        <div className="flex gap-4 flex-col">
          {data.map((item) => (
            <div key={item.id} className="flex gap-4 overflow-hidden">
              <Button
                type="link"
                onClick={() => {
                  importFilterData(theId, {
                    filter_id: item.id
                  }).then(() => {
                    message.success('导入成功')
                  })
                }}>
                {item.name}
              </Button>{' '}
              <Text ellipsis={{ tooltip: true }}>{getQuery(item)}</Text>
            </div>
          ))}
          {(pagination.total && <Pagination {...pagination} />) || null}
        </div>
      ),
      onOk: () => {
        console.log('确认')
      },
      onCancel: () => {
        console.log('取消')
        resetCall()
      },
      title: '导入收藏筛选',
      onOpen: () => {
        setData([])
        resetPageAndTriggerRequest()
      }
    }),
    [data, pagination, resetCall, resetPageAndTriggerRequest, theId]
  )
}
